import java.util.Scanner;

public class Test {
    public static int binarySearch(int[] arr, int num) {
        int left = 0;
        int right = arr.length - 1;
        while(left <= right) {
            int middle = left + ((right-left) / 2);//这么算中间数是防止left + right时超出int的范围
            if(num == arr[middle]) {
                return middle;
            } else if (num > arr[middle]) {
                left = middle + 1;
            } else {
                right = middle - 1;
            }
        }
        return -1;//如果查找不到，返回-1
    }

    public static void main(String[] args) {
        int[] arr = {1, 3, 6, 7, 9, 10, 11, 13};//被查找的下标必须是升序的
        //输入要查找的数
        System.out.println("请输入要查找的数：");
        Scanner sc = new Scanner(System.in);
        int input = sc.nextInt();
        int ret = binarySearch(arr,input);

        if(ret == -1) {
            System.out.println("找不到");
        } else {
            System.out.println(input + "所在的下标是" + ret);
        }
        sc.close();
    }
}
